import { pickStateManager, widgetManager } from '@/common/managers';
import { i18n, nmAppLog } from '@/common/utils';
import { IChangeEvent } from '@rjsf/core';
import { CmdDialogForm, KEYBOARD_KEY } from 'nextcae-base';
import { useEffect, useState } from 'react';
import { ElementTypes, schema, uiSchema } from './data';
import { NMMeshBaseCommand, TopoDialogProps } from '@/common/types';
import { mesh } from '@/domain';
import Base from '@/common/cmdBase/cmdBase';
import { PartMaterialField } from '@/components/PartMaterial';
import { useUpdateEffect } from 'ahooks';
// 面网格
function Command({ title, onClose, icon }: TopoDialogProps) {
  const [hintMessage] = useState('进入创建网格单元命令，请选择点');
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState<any>({
    Option: { elementType: ElementTypes.Tri },
    Selection: { source: [] },
  });
  useEffect(() => {
    window.addEventListener('keyup', onKeyUp);
    return () => {
      window.removeEventListener('keyup', onKeyUp);
    };
  }, []);

  const onKeyUp = (e: KeyboardEvent) => {
    // 点击键盘ESC退出命令
    if (e.key === KEYBOARD_KEY.ESC) {
      onClose();
    }
  };

  useEffect(() => {
    widgetManager.hint(hintMessage);
    return () => {
      widgetManager.hint();
    };
  }, [hintMessage]);

  const handleResultSelectChange = (data: IChangeEvent, id: string) => {
    if (!id) return;
    const keys = id.split('_');
    setFormData((state) => {
      const temp = { ...state[keys[1]], ...data.formData[keys[1]] };
      return { ...state, [keys[1]]: temp };
    });
  };
  const commend = async (preview: boolean = false) => {
    const params = {
      source: formData.Selection.source.map((it) => Base.makeIdNew(it)),
      elementType: formData.Option?.elementType,
      material: formData.AddTo?.material,
      property: formData.AddTo?.property,
      part: formData.AddTo?.part,
    };
    try {
      setIsLoading(true);
      const meshSplitRes = await mesh.createMeshElement(params);
      if (!preview) {
        // 分割完成后，刷新当前视图
        setFormData((state) => ({ ...state, Selection: { source: [] } }));
        pickStateManager.reset();
      } else {
        // TODO 分割预览
        nmAppLog('meshSplitRes', meshSplitRes);
      }
    } finally {
      setIsLoading(false);
    }
  };
  const [execute, setExecute] = useState(false);
  useUpdateEffect(() => {
    if (formData.Option?.elementType === ElementTypes.Tri) {
      if (formData.Selection.source?.length === 3) {
        pickStateManager.next();
        setExecute(true);
      }
    } else {
      if (formData.Selection.source?.length === 4) {
        pickStateManager.next();
        setExecute(true);
      }
    }
  }, [formData.Selection.source, formData.Option]);
  useUpdateEffect(() => {
    pickStateManager.reset();
    setExecute(false);
    setFormData((state) => ({ ...state, Selection: { source: [] } }));
  }, [formData.Option]);
  return (
    <CmdDialogForm
      title={title}
      formData={formData}
      titleIcon={icon}
      submitLoading={isLoading}
      onSubmit={() => commend()}
      onChange={handleResultSelectChange}
      schema={schema}
      extraUiSchema={uiSchema}
      isFormDataValid={execute}
      fields={{
        partMaterialField: PartMaterialField,
      }}
      onClose={onClose}></CmdDialogForm>
  );
}
export const cmdMeshCreate: NMMeshBaseCommand = {
  id: 'cmdMeshCreate',
  icon: 'commands/mesh/mesh-create-element',
  label: 'command.mesh.meshCreate',
  create: (label: string, onClose: () => void) => (
    <Command
      title={i18n.t(label)}
      onClose={onClose}
      icon={cmdMeshCreate.icon}
    />
  ),
};
